import { Component } from 'react'
import Taro from '@tarojs/taro'
import {get,post,put,BASE_URL,channel} from './utils/request'
import {sourceUrl,appid,customeAppId,appid_h5} from '@/utils/serviceSwitching'
import {handleGetLocation, toast} from './utils/index'
import { getAppConfig } from '@/dataTransfer/appConfig';
import { setServerDateNowToGlobal } from '@/dataTransfer/coupon.js';
import wx from '@/utils/weixin-js-sdk/index.js'
import utils from '@/utils/index';
import { Provider } from 'react-redux';
import models from './models';
import dva from './dva';
import './app.scss'

const dvaApp = dva.createApp({
  initialState: {},
  models: models,
});
const store = dvaApp.getStore();

Taro.$get = get
Taro.$post = post
Taro.$put = put
Taro.BASE_URL = BASE_URL
Taro.$sassAppId = customeAppId
Taro.$channel = channel
Taro.$sourceUrl = sourceUrl
Taro.$toast = toast
Taro.$mpAppid = appid
Taro.warrantLogin = async function() {
  const {code} = getUrlParam(location.href)
  if(Taro.getStorageSync('openID')) return;
  if(!code){
    const redirect_uri = `https://wxgateway.wattsapp.cn/?env=${ENV}&from=wechat_redirect`;
    location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Taro.$mpAppid}&redirect_uri=` + encodeURIComponent(redirect_uri) + '&response_type=code&scope=snsapi_base&state=1';
    return;
  }
  let data = {
    loginType:'WECHAT',
    username: Taro.$mpAppid,
    password:code
  }
  Taro.$post('/mb/logins',data).then(res=>{
    if(res.code != '1'){
      Taro.$toast(res.message)
      setTimeout(() => {
        location.href = location.origin
      }, 1000);
      return;
    }
    const timestamp = new Date().getTime();
    if(res.content.userSource == 'USER'){
      Taro.setStorageSync('user',{
        ...res.content,
        loginType:'WECHAT',
        timestamp
      });
    }
    Taro.setStorageSync('userSource',res.content.userSource)
    Taro.setStorageSync('openID',res.content.openId)
    Taro.setStorageSync('token',res.content.token.accessToken)
    Taro.eventCenter.trigger('updateLogin')
  })
}
Taro.verifyLogin = () => { ///  判断是否登录
  if(!Taro.getStorageSync('token') || Taro.getStorageSync('userSource') !== 'USER'){
    Taro.navigateTo({
      url:'/pages/other/login/index'
    })
    throw false;
  }
}
Taro.handleLogin = (type)=>{
  if(process.env.TARO_ENV == 'h5'){
    var ua = navigator.userAgent.toLowerCase();  
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
      Taro.warrantLogin()
      return;
    }
    Taro.navigateTo({
      url:'/pages/other/login/index'
    })
    return;
  }
  Taro.login({
    success:res=>{
      let loginType = 'WECHAT'
      if(process.env.TARO_ENV === 'tt') loginType = 'DOUYIN'
      if(process.env.TARO_ENV === 'kwai') loginType = 'KUAISHOU'
      if(process.env.TARO_ENV === 'alipay') loginType = 'ALIPAY'
      const data = {
        loginType,
        username: Taro.$mpAppid,
        password:res.code
      }
      Taro.$post('/mb/logins',data).then(res=>{
        if(res.code != '1'){
          Taro.$toast(res.message)
          return;
        }
        const timestamp = new Date().getTime();
        if(res.content.userSource == 'USER'){
          Taro.setStorageSync('user',{
            ...res.content,
            loginType,
            timestamp
          });
        }
        Taro.setStorageSync('openID',res.content.openId)
        Taro.setStorageSync('userSource',res.content.userSource)
        Taro.setStorageSync('token',res.content.token.accessToken)
        Taro.eventCenter.trigger('updateLogin')
        if(type == 'back') Taro.navigateBack()
      })
    }
  })
}
Taro.getOpenId = async ()=>{
  return new Promise(resolve => {
    if(Taro.getStorageSync('openID')){
      resolve(Taro.getStorageSync('openID'))
    }else{
      if(process.env.TARO_ENV == 'h5'){
        resolve(Taro.getStorageSync('openID'))
      }else{
        Taro.login({
          scopes:'auth_base',
          onlyAuthorize:false,
          success:res=>{
            let loginType = 'WECHAT'
            if(process.env.TARO_ENV === 'tt') loginType = 'DOUYIN'
            if(process.env.TARO_ENV === 'kwai') loginType = 'KUAISHOU'
            if(process.env.TARO_ENV === 'alipay') loginType = 'ALIPAY'
            Taro.$get(`/mb/third/openid?type=${loginType}&appId=${Taro.$mpAppid}&code=${res.code}`).then(res=>{
              if(res.code === '1'){
                Taro.setStorageSync('openID',res.content)
                resolve(res.content)
              }
            })
          }
        })
      }
    }
  })
}
Taro.getAuthCode = async ()=>{
  return new Promise(resolve => {
    Taro.login({
      scopes:'auth_base',
      onlyAuthorize:false,
      success:res=>{
        resolve(res.code)
      }
    })
  })
}
Taro.getMedia = (pic)=>{
  const url = pic?(pic.indexOf('http')===0?pic:sourceUrl + pic):'';
  return url
}
Taro.wxsdk = async (url)=>{
	const ret = await Taro.$post('/mb/third/wx/getSignature',{"appId":appid_h5,"url":url || location.href.split('#')[0]})
	if(ret.code == '1'){
		wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: ret.content.appId, // 必填，公众号的唯一标识
				timestamp: ret.content.timestamp+'', // 必填，生成签名的时间戳
				nonceStr: ret.content.nonceStr, // 必填，生成签名的随机串
				signature: ret.content.signature,// 必填，签名
				jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','hideOptionMenu','chooseWXPay','openLocation'] // 必填，需要使用的JS接口列表
		});
		return true;
	}else{
		return false
	}
}

Taro.$setTabbarList = ()=>{
  const routes = Taro.getCurrentPages()
  if(routes[0].route.includes('pages/mainPages/tabsPage/index')){
    Taro.setTabBarStyle({
      color: '#26282A',
      selectedColor: '#FF0D49',
      backgroundColor: '#ffffff',
      borderStyle:"white"
    })
  }else{
    Taro.setTabBarStyle({
      "borderStyle":"black",
      "color": "#96989A",
      "selectedColor": "#FF0D49",
      "backgroundColor": "#000",
    })
  }
}

class App extends Component {
  componentWillMount() {
    getAppConfig()
    utils.getDirectionalCoupons();
    handleGetLocation()
    // 获取 应用设置
    if(process.env.TARO_ENV == 'h5'){
      const oMeta = document.createElement('meta');
			oMeta.name = "referrer";
			oMeta.content = "no-referrer"
			document.head.appendChild(oMeta);
      const timestamp = new Date().getTime();
      const {token} = utils.getParames(location.href)
      if(token){
        Taro.$get('/mb/users','','',{
          token,
          channel:'ih5'
        }).then(res=>{
          if(res.code != '1'){
            Taro.$toast(res.message)
            return;
          }
          Taro.setStorageSync('user',{
            ...res.content,
            token:{accessToken:token},
            loginType: 'USER_MOBILE',
            timestamp
          });
          Taro.setStorageSync('userSource','USER')
          Taro.setStorageSync('token',token)
          Taro.eventCenter.trigger('updateLogin')
        })
      }else{
        Taro.removeStorageSync('user')
        Taro.removeStorageSync('userSource')
        Taro.removeStorageSync('token')
      }
      function onBridgeReady(){
        WeixinJSBridge.invoke('setFontSizeCallback', {'fontSize':0}); 
        WeixinJSBridge.on('menu:setfont', function(){
          WeixinJSBridge.invoke('setFontSizeCallback',{'fontSize':0})
        }); 
      }
      if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }else if (document.attachEvent){
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      }else{
        onBridgeReady()
      }
    }
    utils.getFont();
  }
  async componentDidMount () {
    const { statusBarHeight, windowWidth, model, platform, system } = Taro.getSystemInfoSync();
    let ios = !!(system && system.toLowerCase().search('ios') + 1);
    Taro.$windowWidth = windowWidth;
    Taro.$isH5 = process.env.TARO_ENV === 'h5';
    Taro.$isIphoneX = false;
    Taro.$bottomHight = false;
    Taro.$platform = platform;
    Taro.$navBarExtendHeight = 0;
    if (process.env.TARO_ENV != 'h5') {
      const { height, top } = Taro.getMenuButtonBoundingClientRect();
      Taro.$statusBarHeight = statusBarHeight;
      Taro.$titleHeight = (top - statusBarHeight) * 2 + height;
      if (
        model.indexOf('iPhone X') >= 0 ||
        model.indexOf('iPhone 11') >= 0 ||
        model.indexOf('iPhone 12') >= 0 ||
        model.indexOf('iPhone 13') >= 0 ||
        model.indexOf('iPhone14') >= 0
      ) {
        Taro.$isIphoneX = true;
        Taro.$bottomHight = true;
      }

      if (ios) {
        //下方扩展4像素高度 防止下方边距太小
        Taro.$navBarExtendHeight = 4;
      }
      if(!Taro.getStorageSync('token')){
        Taro.handleLogin()
      }
      const updateManager = Taro.getUpdateManager();
      updateManager.onUpdateReady(() => {
        Taro.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success(res) {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          }
        });
      });
    }else{
      if (navigator.userAgent.indexOf('iPhone') >= 0) {
        Taro.$isIphoneX = true;
        Taro.$bottomHight = true;
      }
      Taro.$statusBarHeight = 0;
      Taro.$titleHeight = 0;
    }
    if(process.env.TARO_ENV === 'tt'){
      get('/act/version/review',{
        channel,
        version:'1.0.0'
      }).then(res=>{
        Taro.$review = res.content.review
      })
    }
    setServerDateNowToGlobal();
  }

  componentDidShow () {}

  componentDidHide () {}

  // this.props.children 是将要会渲染的页面
  render () {
    return <Provider store={store} >
      {this.props.children}
    </Provider>
  }
}

export default App
